<template>
  <div class="effect-count">
    <span>{{ valueShow }}</span>
    <em v-if="content">{{ content }}</em>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watch } from 'vue'
import type { PropType } from 'vue'

export default defineComponent({
  name: 'effectCount',
  props: {
    count: {
      type: Number as PropType<number>,
      default: 0
    },
    content: {
      type: String as PropType<string>,
      default: ''
    },
    playing: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    isFormat: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup(props) {
    const value = ref<number>(0)
    const valueTimer = ref<ReturnType<typeof setTimeout>>()
    const step = Math.ceil(props.count / 20)

    const valueShow = computed(() => {
      return props.isFormat ? formatNumber(value.value) : value.value
    })

    const formatNumber = (num: number, char = ',', length = 3) => {
      let result = ''
      let nums = num.toString().split('.')
      let int = nums[0]
      let decimal = nums[1] ? '.' + nums[1] : ''
      while (int.length > length) {
        result = char + int.slice(-length) + result
        int = int.slice(0, int.length - length)
      }
      if (int) result = int + result
      return result + decimal
    }

    const start = () => {
      valueTimer.value && clearTimeout(valueTimer.value)
      valueTimer.value = setTimeout(() => {
        value.value += step
        if (value.value < props.count) start()
        if (value.value >= props.count) {
          value.value = props.count
          clearTimeout(valueTimer.value)
        }
      }, 50)
    }

    const stop = () => {
      valueTimer.value && clearTimeout(valueTimer.value)
      valueTimer.value = setTimeout(() => {
        value.value -= step
        if (value.value > 0) stop()
        if (value.value <= 0) {
          value.value = 0
          clearTimeout(valueTimer.value)
        }
      }, 50)
      // value.value = 0
      // valueTimer.value && clearTimeout(valueTimer.value)
    }

    watch(
      () => props.playing,
      (val: boolean) => {
        val ? start() : stop()
      }
    )

    return {
      valueShow
    }
  }
})
</script>

<style scoped lang="scss">
.effect-count {
  font-size: 38px;
  font-weight: bolder;

  > span {
    font-size: 90px;
  }
}
</style>
